import time
import jwt

from bbs_server.models import User

JWT_SECRET_KEY = "2333-23333"
EXPIRE_TIME = 3600 * 24     # 单位秒
HEADER_NAME_TOKEN = 'HTTP_TOKEN'

class TokenUtil:

    # return bool
    def check_token(request):
        token = request.META.get(HEADER_NAME_TOKEN)
        if token:
            token = token.replace('Bearer ', '')
            jwt_token = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
            try:
                jwt_token = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
            except:
                return False
            user = User.objects.get(id=jwt_token.get('id'))
            if jwt_token.get('exp') - time.time() < 0:
                return False    # 登录过期
            request.user = user
            print('token checked: ' + str(user.__dict__))
            return True

        return False

    # return {'id': , 'token': }
    def generate_token(user_name, in_password, appended_data=''):
        try:
            user=User.objects.get(name=user_name, password=in_password)
        except:
            return {}
        if user: 
            payload = {
                'exp': time.time() + EXPIRE_TIME,  
                'id': user.id,
            }
            encoded_jwt = jwt.encode(payload, JWT_SECRET_KEY, algorithm='HS256')
            return { 'id': user.id, 'token': encoded_jwt }

        return {}
